package sftpdemo;

import lombok.SneakyThrows;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

public class FileUtil {

  public static final String FILE_BASE_PATH = "D:";


  private FileUtil() {
  }

  /**
   * 檢查文件存儲路徑是否存在,不存在則創建該路徑
   */
  private static void checkBasePathExist() {
    File file = new File(FILE_BASE_PATH);
    if (!file.exists()) {
      try {
        Files.createDirectories(file.toPath());
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  public static String getMultipartFileSuffix(MultipartFile file) {
    return Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf('.'));
  }

  /**
   * 將文件寫入response流内
   *
   * @param path     文件路徑
   * @param realName 下載后的文件名
   * @param response HttpServletResponse
   */
  @SneakyThrows //忽略檢查Files.deleteIfExists方法抛出的異常
  public static void writeFileToResponse(String path, String realName, HttpServletResponse response) {
    path = FILE_BASE_PATH + path;
    Path filePath = Paths.get(path);
    File file = filePath.toFile();
    if (file.exists() && !file.isDirectory()) {
      try {
        setResponseHeader(realName, response);
        ServletOutputStream os = response.getOutputStream();
        Files.copy(filePath, os);
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        Files.deleteIfExists(filePath);
      }
    }
  }

  /**
   * 將流轉存為文件
   *
   * @param inputStream InputStream
   * @param fileName    生成的文件名
   * @return File
   */
  public static File writeStreamToFile(InputStream inputStream, String fileName) {
    Path path = Paths.get(FILE_BASE_PATH + fileName);
    try {
      Files.copy(inputStream, path);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return path.toFile();
  }

  /**
   * 刪除文件
   *
   * @param path 文件路徑
   */
  public static void deleteFile(String path) {
    try {
      Files.deleteIfExists(Paths.get(path));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * 設置HttpServletResponse的頭部
   *
   * @param fileName 文件名
   * @param response HttpServletResponse
   * @throws UnsupportedEncodingException
   */
  private static void setResponseHeader(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
    fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
    String contentStr = "attachment; fileName='%s';filename*=utf-8''%s";
    String contentValue = String.format(contentStr, fileName, fileName.replaceAll("\\+", " "));
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Type", "application/octet-stream");
    response.addHeader("Content-Disposition", contentValue);
  }

  /**
   * 转化MultipartFile
   *
   * @param file
   * @return
   */
//  public static MultipartFile convertToMultiFile(File file) {
//    if (null == file)
//      return null;
//    MultipartFile multipartFile = null;
//    // 这个file对应feignClient中的MultipartFile参数名，写错就会报400："message":"Required request
//    // part 'file' is not present"
//    DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
//            MediaType.MULTIPART_FORM_DATA_VALUE, true, file.getName());
//    try(InputStream input = new FileInputStream(file)) {
//      OutputStream os = fileItem.getOutputStream();
//      IOUtils.copy(input, os);
//    } catch (Exception e) {
//      throw new IllegalArgumentException("Invalid file: " + e, e);
//    }
//    multipartFile = new CommonsMultipartFile(fileItem);
//    return multipartFile;
//  }

}
